<?php

namespace app\admin\controller\express;

use app\admin\library\Export;
use app\admin\model\express\Subscribe;
use app\common\controller\Backend;
use app\common\model\Category;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 批次管理
 *
 * @icon fa fa-circle-o
 */
class Batch extends Backend
{

    /**
     * Batch模型对象
     * @var \app\admin\model\express\Batch
     */
    protected $model = null;
    protected $selectpageFields = "id,batch_no,createtime,createtime_text";
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Batch;
        $this->view->assign("stateList", $this->model->getStateList());
    }

    public function import()
    {
        parent::import();
    }

    /*
     * 改变批次状态
     * */
    public function setState(){
        $params = $this->request->post('row/a');
       /* Db::startTrans();
        try {*/
            $this->model->where('id', 'in', $params['ids'])->setField('state', $params['state']);

           // new \app\admin\model\express\Package()
            $orderList = model('app\admin\model\express\Package')->where('batch_id','in',$params['ids'])->select();
            $orderData = $orderTrackData = [];
        $subscribe = new Subscribe();
            foreach ($orderList as $order){
                $orderData[] = [
                    'id' => $order['id'],
                    'state' => $params['state']
                ];
                $track = model('app\admin\model\express\PackageTrack')->where([
                    'package_id' => $order['id'],
                    'state' => $params['state']
                ])->find();
                if($track){
//                    $orderTrackData[] = [
//                        'id' => $track['id'],
//                        'admin_id' => $this->auth->id,
//                        'memo' => $params['memo'],
//                        'createtime' => time()
//                    ];
                }else{
                    $orderTrackData[] = [
                        'package_id' => $order['id'],
                        'state' => $params['state'],
                        'memo' => $params['memo'],
                        'admin_id' => $this->auth->id,
                        'createtime' => time(),
                    ];
                }

                if($params['state']==6){
                    $template_id = '2Q6WWQRYmZBOLpLSx38HDaHrP-uY0jLGG3ZQFQN000w';  //物流信息提醒
                    $data = [
                        'character_string9' => [
                            'value' => $order['package_no']
                        ],
                        'thing10' => [
                            'value' => "包裹已抵达"
                        ],
                        'time11' => [
                            'value' => date("Y-m-d H:i:s")
                        ]
                    ];
                    $page = 'pages/Packagequery/Packagequery';
                    $subscribe->push($order['user_id'], $template_id, $page, $data);
                }elseif (in_array($params['state'],[0,1,2,3,4,5])){
//                    $template_id = '8hhlzY0_Bn7_5pglJ303TDpo3VW1JaFi3kozEVb4BAo';
//                    $data = [
//                        'character_string4'=>$order['package_no'],
//                        'phrase7'=>$s[(int)$params['state']]
//                    ];
//                    $subscribe->push($order['user_id'], $template_id, '', $data);
                }

                if($params['state']==7){
                    Db::name('express_package')->where('id',$order['id'])->update(['status'=>'sign']);
                }

            }
            model('app\admin\model\express\package')->saveAll($orderData);
            model('app\admin\model\express\PackageTrack')->saveAll($orderTrackData);
        $this->success();
    }

    /*
     * 下载身份证
     * */
    public function download($ids = null){
        $orderList = model('app\admin\model\express\order')->where('batch_id','in',$ids)->select();
        $tmpDir = ROOT_PATH.'public/uploads/zip/';

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }
        $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir . $zipName; // 文件路径
        $zip = new \ZipArchive();

        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                $this->error( '下载失败，文件夹不存在');
            }
        }
        foreach ($orderList as $row){

            $row['address'] = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $row['order_id']])
                ->find();
            //正面
            $image = $row['address']['idcard_merge'];
            if($image){
                $image = ROOT_PATH.'public'.$image;
                $image_end = strrpos($image,'.');
                $image_start = strrpos($image,'/');
                $new_front_file = str_replace(substr($image,$image_start ,$image_end - $image_start),'/'.$row['address']['name'].'_'.$row['address']['idcard'],$image);
                copy($image, $new_front_file);
                //反面

                //抓取图片内容
                $frontFileContent = file_get_contents($new_front_file);
                //添加图片
                $zip->addFromString(basename($new_front_file), $frontFileContent);
            }

        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            $this->error('下载失败，文件不存在或无法下载');
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;
    }

    /*
     * 扫描包裹加入批次
     * */
    public function scanning($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $express_no = $this->request->post('express_no');
            $order = \app\admin\model\express\order::get([
                'express_no' => $express_no
            ],['address']);
            if(!$order){
                $this->error('该包裹不存在');
            }
            $orderOnly = \app\admin\model\express\order::with(['address'])
                ->where('batch_id',$ids)
                ->where(function ($query) use($order){
                    $query->where('address.name' , $order['address']['name'])
                        ->whereOr('address.mobile',$order['address']['mobile'])
                        ->whereOr('address.idcard',$order['address']['idcard']);
                })
                ->find();
            if($orderOnly){
                if($order['address']['name'] == $orderOnly['address']['name']){
                    $this->error('该收件人已存在(收货人姓名重复)');
                }
                if($order['address']['mobile'] == $orderOnly['address']['mobile']){
                    $this->error('该收件人已存在(手机号重复)');
                }
                if($order['address']['idcard'] == $orderOnly['address']['idcard']){
                    $this->error('该收件人已存在(身份证号重复)');
                }
            }

            $params = [
                'batch_id' => $ids,
                'status' => $row['status']
            ];
            $result = false;
            $result = $order->allowField(true)->save($params);
            $number = \app\admin\model\express\order::where('batch_id',$ids)->count();
            $row->allowField(true)->save(['number'=>$number]);
            if($result !== false){
                $this->success();
            }else{
                $this->error();
            }
        }
        return $this->view->fetch();
    }

    /*
     * 导出批次包裹
     * */
    public function export($ids = null)
    {
        $export = new Export();
        $list = model('app\admin\model\express\order')
            ->with(['expressorder','user','goods'])
            ->where('batch_id','in',$ids)->select();

        $expCellName = [
            'index' => '计数',
            'express_no' => '分运单号',
            'address_name' => '收件人姓',
            'goods_name' => '商品名称',
            'tax_no' => '行邮税号',
            'goods_brand' => '物品品牌',
            'goods_sku' => '商品规格型号',
            'number_unit' => '计量',
            'goods_number' => '内件数量',
            'goods_price' => '单件物品申报',
            'goods_number_one' => '件数',
            'order_weight' => '商品毛重',
            'goods_weight' => '商品净重',
            'delivery_name' => '发件人姓名',
            'address_name2' => '收件人姓',
            'address_mobile' => '收件人联系方式',
            'address_province' => '省',
            'address_city' => '市',
            'address_area' => '区',
            'address_address' => '收件地址',
            'address_zip_code' => '邮编',
            'country' => '发件人国别',
            'delivery_city' => '发件人城市',
            'production_country' => '产销国',
            'idcard_id' => '收发件人证件',
            'address_idcard' => '收发件人证件号',
            'delivery_name2' => '英文发件人',
            'delivery_city2' => '英文发件人城市',
            'stop_city' => '英文经停城市',
            'delivery_address' => '英文发件人地址',
            'delivery_address2' => '发件人地址',
            'delivery_mobile' => '发件人电话',
            'address_city2' => '收件人城市',
            'goods_name2' => '英文商品名',
            'production_city' => '产销城市',
        ];

        $newList = [];
        $index = 1;
        foreach ($list as $key => $order) {
            $address = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $order['order_id']])
                ->find();
            $delivery_address = Db::name('express_delivery_address')->where('id',$order['delivery_address_id'])->find();
            $num = 0;
            foreach ($order['goods'] as $goods){
                $tax_no = Category::where('id',$goods['category_id'])->value('tax_no');
                if($num === 0){
                    $data = [
                        'index' => $index,
                        'express_no' => $order['express_no'],
                        'address_name' => $address['name'],
                        'goods_name' => $goods['name'],
                        'tax_no' => $tax_no ? $tax_no : '',
                        'goods_brand' => $goods['brand'],
                        'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                        'number_unit' => $goods['number_unit'],
                        'goods_number' => $goods['number'],
                        'goods_price' => $goods['price'],
                        'goods_number_one' => 1,
                        'order_weight' => $order['weight'],
                        'goods_weight' => bcdiv($goods['weight'],1000,2),
                        'delivery_name' => $delivery_address['name'],
                        'address_name2' => $address['name'],
                        'address_mobile' => $address['mobile'],
                        'address_province' => $address['province'],
                        'address_city' => $address['city'],
                        'address_area' => $address['area'],
                        'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                        'address_zip_code' => $address['zip_code'],
                        'country' => 'BE',
                        'delivery_city' => '布鲁塞尔',
                        'production_country' => '301',
                        'idcard_id' => '1',
                        'address_idcard' => $address['idcard'],
                        'delivery_name2' => $delivery_address['name'],
                        'delivery_city2' => 'bruxelles',
                        'stop_city' => '',
                        'delivery_address' => $delivery_address['address'],
                        'delivery_address2' => '布鲁塞尔',
                        'delivery_mobile' => $delivery_address['mobile'],
                        'address_city2' => $address['city'],
                        'goods_name2' => $goods['brand'],
                        'production_city' => 'bruxelles',
                    ];
                }
                else{

                    $data = [
                        'index' => '',
                        'express_no' => $order['express_no'],
                        'address_name' => $address['name'],
                        'goods_name' => $goods['name'],
                        'tax_no' => $tax_no ? $tax_no : '',
                        'goods_brand' => $goods['brand'],
                        'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                        'number_unit' => $goods['number_unit'],
                        'goods_number' => $goods['number'],
                        'goods_price' => $goods['price'],
                        'goods_number_one' => 1,
                        'order_weight' => $order['weight'],
                        'goods_weight' => bcdiv($goods['weight'],1000,2),
                        'delivery_name' => $delivery_address['name'],
                        'address_name2' => $address['name'],
                        'address_mobile' => $address['mobile'],
                        'address_province' => $address['province'],
                        'address_city' => $address['city'],
                        'address_area' => $address['area'],
                        'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                        'address_zip_code' => $address['zip_code'],
                        'country' => 'BE',
                        'delivery_city' => '布鲁塞尔',
                        'production_country' => '301',
                        'idcard_id' => '1',
                        'address_idcard' => $address['idcard'],
                        'delivery_name2' => $delivery_address['name'],
                        'delivery_city2' => 'bruxelles',
                        'stop_city' => '',
                        'delivery_address' => $delivery_address['address'],
                        'delivery_address2' => '布鲁塞尔',
                        'delivery_mobile' => $delivery_address['mobile'],
                        'address_city2' => $address['city'],
                        'goods_name2' => $goods['brand'],
                        'production_city' => 'bruxelles',
                    ];
                }
                $num ++;
                $newList[] = $data;
            }

            $index++;
        }

        $export->exportExcel(date('Y.m.d').'订单' , $expCellName, $newList);
    }
}
